package connect;

import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;

import com.example.administrator.bluetoothdemo01.util.Constant;
import com.example.administrator.bluetoothdemo01.util.LogUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by Lzz on 8/5/2017.
 */

public class ConnectedThread extends Thread{

    private final BluetoothSocket mSocket;
    private final Handler mHandler;
    private final InputStream mInputStream;
    private final OutputStream mOutputStream;

    public ConnectedThread(BluetoothSocket socket, Handler handler) {
        mSocket = socket;
        mHandler = handler;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mInputStream = inputStream;
        mOutputStream = outputStream;
    }

    @Override
    public void run() {
        byte[] buffer = new byte[1024];
        int len;
        while (true){
            try {
                len = mInputStream.read(buffer);
                if (len>0){
                    Message message = mHandler.obtainMessage(Constant.MSG_GOT_DATA, new String(buffer, 0, len, "utf-8"));
                    mHandler.sendMessage(message);
                }
                LogUtils.logd("message size = "+ len);
            } catch (IOException e) {
                mHandler.sendEmptyMessage(Constant.MSG_DATA_ERROR);
                LogUtils.logd("MSG_DATA_ERROR 数据传输失败（已连接的情况）");
                e.printStackTrace();
                break;
            }

        }
    }

    // 取消连接
    public void cancel() {
        try {
            mSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //写操作
    public void write(byte[] bytes){
        try {
            mOutputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
